package com.teradata.io.bio;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * @Project: cmcchq
 * @Description:
 * @Version 1.0
 * @Throws :
 * @Author: <li>2019/6/14 lyndon Create 1.0
 * @Copyright (c)2019-2019 版权所有
 * @Modified By:
 */
@Slf4j
public class Client {

    private static int DEFAULT_SERVER_PORT = 7777;
    private static String DEFAULT_SERVER_IP = "127.0.0.1";


    public static void send(String expression) {
        send(DEFAULT_SERVER_PORT, expression);
    }

    private static void send(int port, String expression) {

        //System.out.println("算术表达式为：" + expression);
        log.info("算术表达式为：" +  expression);
        Socket socket = null;
        BufferedReader in = null;
        PrintWriter out = null;

        try {
            socket = new Socket(DEFAULT_SERVER_IP, port);

            out = new PrintWriter(socket.getOutputStream(),true);
            out.println(expression);

            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //System.out.println("——结果为：" + in.readLine());
            log.info("——结果为:" + in.readLine());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                    in = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (out != null) {
                out.close();
                out = null;
            }

            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                socket = null;
            }

        }


    }


}
